package com.itheima.reggie.service.impl;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //根据用户id查询dish_id或setmeal_id查询是否有此物品
        ShoppingCart shoppingCartOne = shoppingCartMapper.findUidDidOrSid(shoppingCart);
        //如果shoppingCartOne为空则添加一次
        if (shoppingCartOne == null) {
            //补全数据
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        } else {
            //如果有，则数量 加 1
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() + 1);
            shoppingCartMapper.update(shoppingCartOne);
        }
        return shoppingCartOne;
    }

    //根据当前登入者查看购物车
    @Override
    public List<ShoppingCart> findCartByUserId(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartByUserId(userId);
        return shoppingCartList;
    }
    //清空当前用户购物车
    @Override
    public void clean(Long userId) {
         shoppingCartMapper.clean(userId);
    }
    /*删除购物车选项*/
    @Override
    public void sub(ShoppingCart shoppingCart1,Long userId) {
        //通过菜品id获取菜品的数量
          ShoppingCart shoppingCart = shoppingCartMapper.findDishByDishId(shoppingCart1.getDishId(),userId);
          Integer count = shoppingCart.getNumber();
        //如果总数大于一，删除number则减一
        if (count>1){
            shoppingCart.setNumber(shoppingCart.getNumber()-1);
            shoppingCartMapper.updateNum(shoppingCart);
            return;
        }else {
            shoppingCartMapper.deleteDish(shoppingCart.getDishId(),userId);
        }
    }

}
